package com.android.act;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.MyApp;
import com.android.R;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

public class HomeListDemoActivity extends Activity {

	TextView mTv;
	TextView mTitle;

	private Vibrator mVibrator01 = null;
	private LocationClient mLocClient;
	public static String uploadFile = Environment.getExternalStorageDirectory()
			.getAbsolutePath() + "/wallpaper.jpg";
	private ImageView mv;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home_view);
		initView();
	}

	private void initView() {
		mv = (ImageView) findViewById(R.id.imageView1);
		mTitle = (TextView) findViewById(R.id.titlebar_name);
		mTitle.setVisibility(View.VISIBLE);
		mTitle.setText("功能演示");
		mTv = (TextView) findViewById(R.id.tv_location);
		mLocClient = ((MyApp) getApplication()).mLocationClient;
		((MyApp) getApplication()).mTv = mTv;
		mVibrator01 = (Vibrator) getApplication().getSystemService(
				Service.VIBRATOR_SERVICE);
		((MyApp) getApplication()).mVibrator01 = mVibrator01;
		setLocationOption();
		mLocClient.start();
	}

	public void rightClick(View v) {
		switch (v.getId()) {
		case R.id.button1:
			Intent mIntent = new Intent(HomeListDemoActivity.this,
					MainWebActivity.class);
			startActivity(mIntent);
			break;
		case R.id.button2:
			Intent i = new Intent(HomeListDemoActivity.this, RoutePlan.class);
			startActivity(i);
			break;
		case R.id.button3:
			// Intent mIntent3 = new Intent(HomeListDemoActivity.this,
			// MainWebActivity.class);
			// startActivity(mIntent3);
			showDialog(1);
			break;
		case R.id.button4:

			Intent ii = new Intent(HomeListDemoActivity.this, ItemizedOverlayDemo.class);
			// Bundle mBundle = new Bundle();
			// mBundle.putSerializable("shopList", shoplist);
			// ii.putExtras(mBundle);
			startActivity(ii);

			break;

		}
	}

	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {

		switch (id) {

		case 1:
			return new AlertDialog.Builder(this).setTitle(R.string.setting)
					.setItems(R.array.picFrom, picListener).create();

			// case 2:
			// return new AlertDialog.Builder(this).setTitle(R.string.setting)
			// .setItems(R.array.appFrom, appListener).create();

		default:
			return super.onCreateDialog(id, args);
		}
	}

	DialogInterface.OnClickListener picListener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			if (which == 0) { 
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				// 下面这句指定调用相机拍照后的照片存储的路径
				intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "weibo.jpg")));
				startActivityForResult(intent, 2); 
			} else if (which == 1) {
				Intent intent = new Intent();
				// Type为image
				intent.setType("image/*");
				// Action:选择数据然后返回
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(intent, 1);
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {

			switch (requestCode) { 
			// // 如果是直接从相册获取
			case 1:
				startPhotoZoom(data.getData());
				break;
			// 如果是调用相机拍照时
			case 2:
				File temp = new File(Environment.getExternalStorageDirectory() + "/weibo.jpg");
				startPhotoZoom(Uri.fromFile(temp));
				break;
			// 取得裁剪后的图片
			case 3:
				/**
				 * 非空判断大家一定要验证，如果不验证的话， 在剪裁之后如果发现不满意，要重新裁剪，丢弃
				 * 当前功能时，会报NullException，小马只 在这个地方加下，大家可以根据不同情况在合适的 地方做判断处理类似情况
				 * 
				 */
				if (data != null) {
					setPicToView(data);
				}
				break;
			default:
				break;

			}
		}
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}

	/**
	 * 保存裁剪之后的图片数据
	 * 
	 * @param picdata
	 */
	private void setPicToView(Intent picdata) {
		Bundle extras = picdata.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			// Drawable drawable = new BitmapDrawable(photo);

//			Intent intent = new Intent(HomeListDemoActivity.this, PicUploadActivity.class);
//			intent.putExtra("image", photo);
//			intent.putExtra("picurl", Environment.getExternalStorageDirectory() + "/weibo.jpg");
//
//			startActivity(intent);
			mv.setImageBitmap(photo);

			/**
			 **  下面注释的方法是将裁剪之后的图片以Base64Coder的字符方式上 传到服务器，QQ头像上传采用的方法跟这个类似
			 **/

			/*
			 * ByteArrayOutputStream stream = new ByteArrayOutputStream();
			 * photo.compress(Bitmap.CompressFormat.JPEG, 60, stream); byte[] b
			 * = stream.toByteArray(); // 将图片流以字符串形式存储下来
			 * 
			 * tp = new String(Base64Coder.encodeLines(b));
			 * 这个地方大家可以写下给服务器上传图片的实现，直接把tp直接上传就可以了， 服务器处理的方法是服务器那边的事了，吼吼
			 * 
			 * 如果下载到的服务器的数据还是以Base64Coder的形式的话，可以用以下方式转换 为我们可以用的图片类型就OK啦...吼吼
			 * Bitmap dBitmap = BitmapFactory.decodeFile(tp); Drawable drawable
			 * = new BitmapDrawable(dBitmap);
			 */
			// ib.setBackgroundDrawable(drawable);
			// iv.setBackgroundDrawable(drawable);
		}
	}

	private void setLocationOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true); // 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setServiceName("com.baidu.location.service_v2.9");
		option.setPoiExtraInfo(true);

		option.setAddrType("all");
		option.setScanSpan(10000);// 设置定位模式，小于1秒则一次定位;大于等于1秒则定时定位

		// option.setPriority(LocationClientOption.NetWorkFirst); // 设置网络优先

		option.setPriority(LocationClientOption.GpsFirst); // 不设置，默认是gps优先
		// }

		option.setPoiNumber(10);
		option.disableCache(true);
		mLocClient.setLocOption(option);
	}

	@Override
	protected void onPause() {
		mLocClient.stop();
		super.onPause();
	}

	@Override
	protected void onResume() {
		// mLocClient.start();
		// new AsyncDataLoader(asyncSQCallback).execute();
		super.onResume();
	}

	@Override
	public void onDestroy() {
		mLocClient.stop();
		((MyApp) getApplication()).mTv = null;
		super.onDestroy();
	}
	
	
	private void upload() {
		HttpURLConnection connection = null;
		DataOutputStream outputStream = null;
		DataInputStream inputStream = null;

		String pathToOurFile = uploadFile;
		String urlServer = "http://10.10.13.10/apps/utest/file/index.php";
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";

		int bytesRead, bytesAvailable, bufferSize;
		byte[] buffer;
		int maxBufferSize = 1 * 1024 * 1024;

		try {
			FileInputStream fileInputStream = new FileInputStream(new File(
					pathToOurFile));

			URL url = new URL(urlServer);
			connection = (HttpURLConnection) url.openConnection();

			// Allow Inputs & Outputs
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);

			// Enable POST method
			connection.setRequestMethod("POST");

			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);

			outputStream = new DataOutputStream(connection.getOutputStream());
			outputStream.writeBytes(twoHyphens + boundary + lineEnd);
			outputStream
					.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
							+ pathToOurFile + "\"" + lineEnd);
			outputStream.writeBytes(lineEnd);

			bytesAvailable = fileInputStream.available();
			bufferSize = Math.min(bytesAvailable, maxBufferSize);
			buffer = new byte[bufferSize];

			// Read file
			bytesRead = fileInputStream.read(buffer, 0, bufferSize);

			while (bytesRead > 0) {
				outputStream.write(buffer, 0, bufferSize);
				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			}

			outputStream.writeBytes(lineEnd);
			outputStream.writeBytes(twoHyphens + boundary + twoHyphens
					+ lineEnd);

			// Responses from the server (code and message)
			int serverResponseCode = connection.getResponseCode();
			String serverResponseMessage = connection.getResponseMessage();
			showDialog(serverResponseMessage);
			fileInputStream.close();
			outputStream.flush();
			outputStream.close();
		} catch (Exception ex) {
			// Exception handling
		}
	}
	
	/* 显示Dialog的method */
	private void showDialog(String mess) {
		new AlertDialog.Builder(HomeListDemoActivity.this).setTitle("Message")
				.setMessage(mess)
				.setNegativeButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
				}).show();
	}
}
